package com.sun.decrypt;

import org.apache.commons.codec.binary.Base64;
import org.junit.Test;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

public class DesTest {
    private static final String ALGORITHM = "DES";
    private static final String KEY = "12345678";
    private static final String UTF8 = StandardCharsets.UTF_8.name();

    @Test
    public void test1(){
        String str = "哈喽哈";
        String encrypt = encrypt(str);
        System.out.println("base64编码des加密后的结果 " + encrypt);
        String decrypt = decrypt(encrypt);
        System.out.println("解码后的数据 " + decrypt);
    }

    /**
     * 加密
     * @param str 待加密字符串
     * @return
     */
    public  String encrypt(String str){
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            SecretKey key = new SecretKeySpec(KEY.getBytes(UTF8),ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE,key);
            byte[] bytes = cipher.doFinal(str.getBytes(UTF8));
            return Base64.encodeBase64String(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 解密
     * @param str 待解密字符串
     * @return
     */
    public  String decrypt(String str){
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            SecretKey key = new SecretKeySpec(KEY.getBytes(UTF8),ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE,key);
            byte[] bytes = cipher.doFinal(Base64.decodeBase64(str.getBytes(UTF8)));
            return new String(bytes,UTF8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
